//
//  WYOAuthViewController.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/10.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking

//MARK -- 定义属性
let WeiboAppKey = "936769838"
let WeiboAppSecret = "6b3362beb2f08ed629e99ccb070b438b"
let WeiboRedirect_Uri = "http://www.baidu.com"


//遵守协议
class WYOAuthViewController: UIViewController, UIWebViewDelegate {
    
    //MARK -- 懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        
        //自定义试图
        webView.delegate = self
        view = webView
    
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupNavUI()
        requestOAuthLogin()
    }
    
    //MARK -- 请求登陆地址
    private func requestOAuthLogin() {
        
        //获取登陆地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
      
        print(url)
        
        //准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //加载数据
        webView.loadRequest(request)
        
    }
    
    //设置导航栏属性
    private func setupNavUI() {
    
        navigationItem.title = "微博登陆"
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target:  self, action: "autoFileAction")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:  self, action: "cancelAction")
        
    }
    
    // MARK: -- 点击事件
    //取消
    @objc private func cancelAction() {
    
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充
    @objc private func autoFileAction() {
        
        print("自动填充")
    //get 可以直接拼接
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '740149961@qq.com'; document.getElementById('passwd').value = 'wangyi0212'")
        
    }

//    
//    //MARK -- 通过授权码(code)获取 accesstoken
//    
//    private func requestAccesstoken(code: String) {
//        
//        
//        WYNetWorkingTools.sharedTools.requestAccesstoken(code) { (response, error) -> () in
//            if error != nil {
//            
//                print(error)
//                return
//            }
//            //代码执行到此成功的回调
//            guard let dic = response as? [String: AnyObject] else{
//                
//                print("不是一个正确的 json")
//                return
//                
//            }
//            
//            let userAccount = WYUserAccount(dict: dic)
//            
//            print(userAccount)
//            //通过 accessTpken 和 uid 获取用户信息
//            self.requestUserInfos(userAccount)
//            
//        }
//        
    
//        //获取网址https://api.weibo.com/oauth2/access_token
//        let url = "https://api.weibo.com/oauth2/access_token"
//        //返回值 参数
//        let prams = [
//            "client_id": WeiboAppKey,
//            "client_secret": WeiboAppSecret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WeiboRedirect_Uri
//        ]
//        
//        let sessionMessager = AFHTTPSessionManager()
//        sessionMessager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        //发送请求
//        sessionMessager.POST(url, parameters: prams, progress: nil, success: { (_, response) -> Void in
//            
//                print(response)
//            
//            }) { (_, error) -> Void in
//               
//                print(error)
//        }
//    }
    
//    //获取用户信息
//    private func requestUserInfos(userAccount: WYUserAccount) {
//        
//        //根据模型 加载数据  如果得到返回值就执行下面代码
//       WYNetWorkingTools.sharedTools.requestUserInfos(userAccount) { (response, error) -> () in
//        if error != nil {
//        
//            print(error)
//            return
//        }
//        guard let dic = response as? [String: AnyObject] else {
//        
//            print("这不是一个正确的 JSON ")
//            return
//        }
//        
//        let name = dic["name"]
//        let avatar_large = dic["avatar_large"]
//        
//        userAccount.name = name as? String
//        userAccount.avatar_large = avatar_large as? String
//        
//        userAccount.saveUserAccount()
//        print(userAccount)
//        
//        }
    
//        //根据新浪微博 用户信息得到
//        //获取 URL https://api.weibo.com/2/users/show.json
//        let url = "https://api.weibo.com/2/users/show.json"
//        
//        //int64 跟字符串放在一起编译不通过 需要转化为字符串
//        let params = [
//        
//            "access_token": userAccount.access_token!,
//            "uid": "\(userAccount.uid)"
//        ]
//        //由于使用 get 方式请求
//        let urlStr = url + "?access_token=\(userAccount.access_token!)&uid=\(userAccount.uid)"
//        print(urlStr)
//        
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.GET(urlStr, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            guard let dic = response as? [String: AnyObject] else {
//            
//                print("这不是一个正确的json值")
//                return
//            }
//            //代码执行到这里 一定有值
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//            
//            //设置用户名和图像
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            
//            print(userAccount)
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
        
    }
  //}


extension WYOAuthViewController {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else {
        
            return false
        }
        //代码 执行到此 
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
        
            return true
        }
        
        if let query = url.query where query.hasPrefix("code=") {
        //代码执行到此 关心的 URL 字符串
            let code = query.substringFromIndex("code=".endIndex)
            
            print(code)
//                    requestAccesstoken(code)
            WYUserAccountViewModel.sharedUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    print ("登陆成功")
                    
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })

                } else {
                
                    print("登陆失败")
                    SVProgressHUD.showErrorWithStatus("登陆失败")
                }
//
            })
        } else {
            
                dismissViewControllerAnimated(true, completion: nil)
            }
        return false
    }
    
    
    
    
    
    //MARK -- 代理方法
    //加载开始
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
        
        SVProgressHUD.show()
    }

}

